<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" ref="listQuery">
        <el-form-item label=""  prop="authorityName">
          <el-input @keyup.enter.native="searchFilter"  style="width: 200px;" class="filter-item" placeholder="权限名" v-model="listQuery.authorityName">
          </el-input>
        </el-form-item>
        <el-form-item label=""  prop="authorityCode">
          <el-input @keyup.enter.native="searchFilter"  style="width: 200px;" class="filter-item" placeholder="权限编码" v-model="listQuery.authorityCode">
          </el-input>
        </el-form-item>
        <el-form-item label=""  prop="status">
            <el-select clearable style="width: 100px" class="filter-item" v-model="listQuery.status" placeholder="状态">
              <el-option
                v-for="item in statusArray"
                :label="item.value"
                :value="item.code">
              </el-option>
            </el-select>
        </el-form-item>
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="searchFilter">搜索</el-button>
        <el-button class="filter-item" type="primary" v-waves  @click="resetForm('listQuery')">重置</el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="save" >添加</el-button>
      </el-form>
    </div>

    <el-table :data="tableData" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
              :default-sort = "{prop: 'createTime', order: 'descending'}">
      <el-table-column align="center" label='ID' width="95">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="菜单名称" sortable width="120" align="center" prop="menuName">
        <template slot-scope="scope">
          <span>{{scope.row.menuName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限名称" sortable width="120" align="center" prop="authorityName">
        <template slot-scope="scope">
          <span>{{scope.row.authorityName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限编码" sortable width="120" align="center" prop="authorityCode">
        <template slot-scope="scope">
          <span>{{scope.row.authorityCode}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" sortable label="权限url" width="110" align="center" prop="url">
        <template slot-scope="scope">
          {{scope.row.url}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" sortable label="状态" width="110" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="creator" label="创建人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.creator}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="createTime" label="创建时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"sortable prop="updater" label="修改人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.updater}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="updateTime" label="修改时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.updateTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="250" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" v-if="scope.row.status === '0'" size="mini" @click="enable(scope.row)">启用</el-button>
          <el-button type="primary" v-if="scope.row.status === '1'" size="mini" @click="disable(scope.row)">禁用</el-button>
          <el-button type="primary" size="mini" @click="edit(scope.row)">修改</el-button>
          <el-button type="danger"  size="mini" @click="deleteAuthority(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum"
                     :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--新增模态框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-position="left" label-width="80px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="菜单" prop="menuId">
          <el-select v-model="ruleForm.menuId" filterable clearable  placeholder="请选择">
            <el-option
              v-for="item in menuList"
              :key="item.id"
              :label="item.menuName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限名称" prop="authorityName">
          <el-input v-model.trim="ruleForm.authorityName"></el-input>
        </el-form-item>
        <el-form-item label="权限编码" v-if="dialogStatus=='create'" prop="authorityCode">
          <el-input v-model.trim="ruleForm.authorityCode"/>
        </el-form-item>
        <el-form-item label="权限url"  prop="url">
          <el-input v-model.trim="ruleForm.url"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model.trim="ruleForm.status" label="1">启用</el-radio>
          <el-radio v-model.trim="ruleForm.status" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="saveAuthorityData">确 定</el-button>
        <el-button v-else type="primary" @click="updateAuthority">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getListPage, deleteAuthority, enableAuthority, disableAuthority, modifyAuthority, saveAuthority, checkAuthorityCode, getMenuList } from '@/api/authority'
import waves from '@/directive/waves' // 水波纹指令
import { isValidAuthorityCode, isValidAuthorityName } from '@/utils/validate'
export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    const validateAuthorityCode = (rule, value, callback) => {
      if (!isValidAuthorityCode(value)) {
        callback(new Error('权限编码格式不合法'))
      } else {
        const param = {}
        param.authorityCode = value
        if (this.dialogStatus === 'update') {
          param.authorityId = this.ruleForm.id
        }
        checkAuthorityCode(param).then(response => {
          if (response) {
            callback(new Error('权限编码已存在'))
          } else {
            callback()
          }
        })
      }
    }
    const validateAuthorityName = (rule, value, callback) => {
      if (!isValidAuthorityName(value)) {
        callback(new Error('权限名称格式不合法'))
      } else {
        callback()
      }
    }
    return {
      tableData: null,
      listLoading: true,
      total: 0,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        authorityName: '',
        authorityCode: '',
        status: ''
      },
      menuList: [],
      statusArray: [
        {
          code: '1',
          value: '启用'
        },
        {
          code: '0',
          value: '禁用'
        }
      ],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      downloadLoading: false,
      ruleForm: {
        id: '',
        authorityName: '',
        authorityCode: '',
        menuId: '',
        status: '1',
        url: ''
      },
      rules: {
        authorityName: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '权限名称长度为2到20个字符', trigger: 'blur' },
          { validator: validateAuthorityName, trigger: 'blur' }
        ],
        authorityCode: [
          { required: true, message: '权限编码不能为空', trigger: 'blur' },
          { validator: validateAuthorityCode, trigger: 'blur' }
        ],
        url: [
          { required: true, message: 'URL不能为空', trigger: 'blur' },
          { min: 2, max: 30, message: '权限名称长度为2到30个字符', trigger: 'blur' }
        ],
        menuId: [
          { required: true, message: '菜单不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '启用',
        0: '禁用'
      }
      return statusMap[status]
    }
  },
  created() {
    this.fetchData()
    this.getMenuList()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getListPage(this.listQuery).then(response => {
        this.tableData = response.list
        this.total = response.total
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.fetchData()
    },
    getMenuList() {
      this.listLoading = true
      getMenuList().then(response => {
        this.menuList = response
        this.listLoading = false
      })
    },
    save() {
      this.resetAuthorityData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate()
      })
    },
    saveAuthorityData() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          saveAuthority(this.ruleForm).then(response => {
            if (response === 1) {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },
    resetAuthorityData() {
      this.ruleForm = {
        authorityName: '',
        authorityCode: '',
        status: '1',
        url: '',
        menuId: ''
      }
    },
    edit(row) {
      this.ruleForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate()
      })
    },
    updateAuthority() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          modifyAuthority(this.authority).then(response => {
            if (response === 1) {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },
    deleteAuthority(row) {
      this.$confirm(`确定删除权限${row.authorityName}吗？`, '删除提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        deleteAuthority(row.id).then(response => {
          if (response === 1) {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    searchFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    resetForm(form) {
      this.$refs[form].resetFields()
      this.fetchData()
    },
    enable(row) {
      this.$confirm(`确定启用权限${row.authorityName}吗？`, '启用提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        enableAuthority(row.id).then(response => {
          if (response === 1) {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '启用成功!'
            })
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消启用'
        })
      })
    },
    disable(row) {
      this.$confirm(`确定禁用权限${row.authorityName}吗？`, '禁用提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        disableAuthority(row.id).then(response => {
          if (response === 1) {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '禁用成功!'
            })
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用'
        })
      })
    }
  }
}
</script>
